import React, { memo,useState,useEffect ,useRef} from 'react'
import { useSelector } from "react-redux";
import { Button, Card,Table,Modal ,Form,Input,message,Tree } from 'antd';
import moment from "moment";
import { PlusCircleOutlined } from '@ant-design/icons';
import { reqRoleList,reqAddRole,reqUpdateRole } from "@/network";
import authList from "@/common/auth_config";
import { PAGE_SIZE } from "@/common";

export default memo(function HjRole() {

  // props state
  const [isRoleVisible, setIsRoleVisible] = useState(false);//是否显示角色弹窗
  const [isAuthVisible, setIsAuthVisible] = useState(false);//是否显示权限弹窗
  const [roleList, setRoleList] = useState([]);//权限列表
  const [isLoading, setIsLoading] = useState(true);//是否加载完毕
  const [roleId, setroleId] = useState('');//点击的这个角色id
  const [username, setUsername] = useState('');//当前账号的用户名  授权人姓名
  // -------tree state---------
  const [checkedKeys, setCheckedKeys] = useState([]);//选中的节点的key 选中的权限（需要更新的权限）
  
  // reudx hooks 
  const {user} = useSelector(state => ({
    user:state.userInfo.user
  }))
  // other hooks
  const roleFormRef = useRef()
  useEffect(() => {
    getRoleList()
    // 将授权人姓名保存到组件中
    setUsername(user.username)
  }, [user]);


const columns = [
  {
    title: '角色名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    key: 'create_time',
    render:(create_time)=>(moment(create_time).format('YYYY-MM-DD, h:mm:ss'))
  },
  {
    title: '授权时间',
    dataIndex:'auth_time',
    key: 'auth_time',
    render:(auth_time)=>(auth_time?moment(auth_time).format('YYYY-MM-DD, h:mm:ss'):'')
  },
  {
    title: '授权人',
    dataIndex:'auth_name',
    key: 'auth_name'
  },
  {
    title: '操作',
    //dataIndex:'opera',
    key: 'opera',
    render :(item)=>(<Button type="link" onClick={()=>{setAuth(item)}}>设置权限</Button>)
  }
]
  
  // handle function
  // 发请求获取角色列表
  const getRoleList = async()=>{
    const result = await reqRoleList()
    setIsLoading(false)
    const {status,data}=result
    if(status===0)setRoleList(data)

  } 
  // 发请求设置授权
  const getUpdateRole = async()=>{
    const  authObj = {_id:roleId,menus:checkedKeys,auth_name:username,auth_time:Date.now()}
    const result = await reqUpdateRole(authObj)
    const {status,msg}=result
    if(status===0){
      // 修改过权限后，更新权限列表
      getRoleList()
      message.success('设置权限成功')
    }
    else message.error(msg)
  } 

  // 确定新增角色
  const handleRoleOk = ()=>{
    // 验证添加角色表单,验证成功后发请求添加角色
    roleFormRef.current.validateFields()
    .then(async(value)=>{
        const result = await reqAddRole(value)
         const {status,msg,data}=result
        if(status===0){
          message.success('新增角色成功！！')
          setRoleList([...roleList,data])
        }else{
          message.error(msg)
        }
    })
    .catch(error=>{})

    setIsRoleVisible(false)
    
    // 搞个定时器，做个延时，清空新增角色弹窗
    setTimeout(() => {
      roleFormRef.current.resetFields()
    }, 1000);

  }
  const handleCancel = ()=>{
    setIsRoleVisible(false)
    setIsAuthVisible(false)
  }
  // 确定权限
  const handleAuthOk = ()=>{
      getUpdateRole()
      setIsAuthVisible(false)
  }

  // 新增角色的按钮
  const addRole = ()=>{
     setIsRoleVisible(true)
  }
  // 点击设置权限的按钮
  const setAuth = (item)=>{
    const {_id} = item
    setroleId(_id)
  // 根据角色id找到对应的角色，然后找到对应的选中的节点的key用于数据回显 tree
   const currentRole = roleList.find(item=>{
      return item._id ===_id
   })
  //  设置默认的tree对应的选中的节点的key用于数据回显
   setCheckedKeys(currentRole.menus)
   setIsAuthVisible(true)
    

  }

// ------tree function-------------------------
 const onCheck = (checkedKeysValue) => {
    setCheckedKeys(checkedKeysValue);
  };
    return (
       <div>
      <Card 
          title={<Button type="primary" onClick={addRole} icon={<PlusCircleOutlined/>}>新增角色</Button>} >
           <Table 
                  dataSource={roleList} 
                  columns={columns} 
                  rowKey="_id"
                  bordered
                  showHeader
                  loading={isLoading}
                   pagination={
                        {
                        pageSize:PAGE_SIZE,
                        defaultCurrent:1,
                      }}
                  />;
      </Card>
         {/* 新增角色的对话框 */}
           <Modal 
                title='新增角色'
                visible={isRoleVisible} 
                onOk={handleRoleOk} 
                onCancel={handleCancel}
                okText="确定"
                cancelText="取消">

                  <Form
                    name="roleForm"
                    autoComplete="off"
                    ref={roleFormRef}
                  >
                      <Form.Item
                         name="roleName"
                         rules={[{ required: true, message: '角色名称必须输入！！' }]}
                      >
                        <Input placeholder="输入角色名称"/>
                      </Form.Item>
                   </Form>
          </Modal>
           {/* 权限的对话框 */}
           <Modal 
                title='设置权限'
                visible={isAuthVisible} 
                onOk={handleAuthOk} 
                onCancel={handleCancel}
                okText="确定"
                cancelText="取消">

                  <Form
                    name="authForm"
                    autoComplete="off"
                    
                  >
                      <Form.Item
                         name="authnName"
                        //  rules={[{ required: true, message: '分类名必须输入！！' }]}
                      >
                       <Tree
                          checkable //是否支持选中
                          onCheck={onCheck}
                          checkedKeys={checkedKeys}// 默认选中复选框的树节点
                          defaultExpandAll
                          treeData={authList}
                        />
                      </Form.Item>
                   </Form>
          </Modal>
    </div>
    )
})
